import { createAdapter } from '@socket.io/redis-adapter'
import Redis from 'ioredis'
import { Server } from 'socket.io'
import { config } from '../../config'
import logger from '../../utils/logger'

class ChatService {
  private io: Server
  private redis: Redis

  constructor() {
    this.redis = new Redis(config.redis)
  }

  initialize(io: Server) {
    this.io = io

    // 使用Redis适配器实现多进程
    const pubClient = new Redis(config.redis)
    const subClient = pubClient.duplicate()
    io.adapter(createAdapter(pubClient, subClient))

    // 处理连接
    io.on('connection', (socket) => {
      logger.info(`Client connected: ${socket.id}`)

      // 加入房间
      socket.on('joinRoom', (roomId: string) => {
        socket.join(roomId)
        socket.to(roomId).emit('userJoined', {
          userId: socket.data.userId,
          username: socket.data.username,
        })
      })

      // 发送消息
      socket.on('message', async (data) => {
        const { roomId, content } = data

        // 发送到房间
        io.to(roomId).emit('message', {
          userId: socket.data.userId,
          username: socket.data.username,
          content,
          timestamp: Date.now(),
        })
      })
    })
  }
}

export const chatService = new ChatService()
